package view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import util.DBUtil;

public class paper extends JFrame {
    private JPanel contentPane;
    private List<Question> questions;
    private int currentQuestionIndex = 0;
    private int score = 0;

    // 界面组件
    private JLabel questionLabel;
    private JRadioButton[] optionButtons;
    private ButtonGroup optionGroup;
    private JButton nextButton;
    private JButton submitButton;
    private JLabel progressLabel;

    public paper() {
        setTitle("试卷生成");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 800, 600);

        contentPane = new JPanel();
        contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 20));

        // 初始化试题数据
        initQuestionsFromDB();

        // 顶部进度标签
        progressLabel = new JLabel("", JLabel.CENTER);
        progressLabel.setFont(new Font("宋体", Font.BOLD, 16));
        contentPane.add(progressLabel, BorderLayout.NORTH);

        // 中间题目面板
        JPanel questionPanel = new JPanel();
        questionPanel.setLayout(new BorderLayout(0, 20));

        questionLabel = new JLabel("", JLabel.LEFT);
        questionLabel.setFont(new Font("宋体", Font.PLAIN, 18));
        questionPanel.add(questionLabel, BorderLayout.NORTH);

        // 选项面板
        JPanel optionsPanel = new JPanel();
        optionsPanel.setLayout(new GridLayout(4, 1, 0, 10));
        optionButtons = new JRadioButton[4];
        optionGroup = new ButtonGroup();

        for (int i = 0; i < 4; i++) {
            optionButtons[i] = new JRadioButton();
            optionButtons[i].setFont(new Font("宋体", Font.PLAIN, 16));
            optionGroup.add(optionButtons[i]);
            optionsPanel.add(optionButtons[i]);
        }

        questionPanel.add(optionsPanel, BorderLayout.CENTER);
        contentPane.add(questionPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));

        nextButton = new JButton("下一题");
        nextButton.setFont(new Font("宋体", Font.BOLD, 16));
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                checkAnswer();
                showNextQuestion();
            }
        });

        submitButton = new JButton("提交试卷");
        submitButton.setFont(new Font("宋体", Font.BOLD, 16));
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                checkAnswer();
                showResult();
            }
        });
        submitButton.setVisible(false);

        buttonPanel.add(nextButton);
        buttonPanel.add(submitButton);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        // 显示第一题
        if (!questions.isEmpty()) {
            showQuestion(0);
        } else {
            JOptionPane.showMessageDialog(this, "没有找到试题！", "错误", JOptionPane.ERROR_MESSAGE);
            dispose();
        }
    }

    // 从数据库初始化试题数据
    private void initQuestionsFromDB() {
        questions = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConn();
            String sql = "SELECT question_text, option_a, option_b, option_c, option_d, correct_answer FROM questions";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                String questionText = rs.getString("question_text");
                String optionA = "A. " + rs.getString("option_a");
                String optionB = "B. " + rs.getString("option_b");
                String optionC = "C. " + rs.getString("option_c");
                String optionD = "D. " + rs.getString("option_d");
                String correctAnswer = rs.getString("correct_answer");

                questions.add(new Question(
                        questionText,
                        new String[]{optionA, optionB, optionC, optionD},
                        correctAnswer
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载试题失败！", "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            try {
                if (rs != null) rs.close();
                if (ps != null) ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBUtil.closeConn();
        }
    }

    // 显示指定索引的题目
    private void showQuestion(int index) {
        if (index < 0 || index >= questions.size()) return;

        Question q = questions.get(index);
        questionLabel.setText(q.getQuestionText());

        for (int i = 0; i < 4; i++) {
            optionButtons[i].setText(q.getOptions()[i]);
            optionButtons[i].setSelected(false);
        }

        // 更新进度标签
        progressLabel.setText(String.format("题目 %d/%d", index + 1, questions.size()));

        // 如果是最后一题，显示提交按钮
        if (index == questions.size() - 1) {
            nextButton.setVisible(false);
            submitButton.setVisible(true);
        } else {
            nextButton.setVisible(true);
            submitButton.setVisible(false);
        }
    }

    // 显示下一题
    private void showNextQuestion() {
        currentQuestionIndex++;
        showQuestion(currentQuestionIndex);
    }

    // 检查当前题目答案
    private void checkAnswer() {
        Question q = questions.get(currentQuestionIndex);

        for (int i = 0; i < 4; i++) {
            if (optionButtons[i].isSelected()) {
                String selectedOption = optionButtons[i].getText().substring(0, 1);
                if (selectedOption.equals(q.getCorrectAnswer())) {
                    score++;
                }
                break;
            }
        }
    }

    // 显示考试结果
    private void showResult() {
        double percentage = (double)score / questions.size() * 100;
        String message = String.format(
                "考试结束！\n\n答对题数: %d/%d\n得分: %.1f%%\n\n%s",
                score, questions.size(), percentage,
                percentage >= 60 ? "恭喜通过考试！" : "很遗憾未通过，请继续努力！"
        );

        JOptionPane.showMessageDialog(this, message, "考试结果", JOptionPane.INFORMATION_MESSAGE);
        dispose(); // 关闭试卷窗口
    }

    // 题目内部类
    private class Question {
        private String questionText;
        private String[] options;
        private String correctAnswer;

        public Question(String questionText, String[] options, String correctAnswer) {
            this.questionText = questionText;
            this.options = options;
            this.correctAnswer = correctAnswer;
        }

        public String getQuestionText() { return questionText; }
        public String[] getOptions() { return options; }
        public String getCorrectAnswer() { return correctAnswer; }
    }
}